package com.atguigu.controller;

import com.atguigu.pojo.SysUser;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.WebServlet;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user/changepassword")
public class UserChangePasswordController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            /**
             * 我们应该先根据当前登录的用户id查询对应的用户
             * 然后再service层拿出用户的密码,和我们在页面上
             * 填写的原始密码比较一样才能更新新密码
             */
            SysUser sysUser = (SysUser) request.getSession().getAttribute("user");
            Integer uid = sysUser.getId();

            //获取页面的原始密码和新密码
            String password = request.getParameter("password");
            String newpassword = request.getParameter("newpassword");
            boolean b = userService.updateUserPassword(uid, password, newpassword);
            if (b) {
                request.setAttribute("message", "修改密码成功");
                request.getRequestDispatcher("/password.jsp").forward(request, response);
            } else {
                request.setAttribute("message", "修改密码失败");
                request.getRequestDispatcher("/password.jsp").forward(request, response);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}